const { Controller } = require("egg")

class SkuParamsController extends Controller {
    async getSkuParams() {
        const { ctx } = this;
        let data = await ctx.model.SkuParams.find().lean();
        function build(parentId, children = []) {
            return data.filter(item => item.parentId == parentId).sort((a, b) => a.sort - b.sort).map(item => ({ ...item, children: build(item._id, children) }))
        }
        data = build(null)
        ctx.send({ msg: "成功", data })
    }
    async updateSkuParams() {
        const { ctx } = this;
        const { _id, label, parentId = null } = ctx.request.body;
        ctx.validate({
            label: { type: "nullValue", fieldName: "标签" }
        });
        let res;
        if (_id) {
            console.log("更新啊");
            res = await ctx.model.SkuParams.findByIdAndUpdate(_id, { label, parentId });
            console.log(res);
        } else {
            const lastParams = await ctx.model.SkuParams.find({ parentId }).sort({ sort: -1 }).limit(1)
            console.log("//////////", lastParams);
            res = await ctx.model.SkuParams.create({ label, parentId, sort: lastParams[0] ? lastParams[0].sort + 1 : 0 })
        }
        ctx.send({ msg: "成功", data: res })
    }

    async delSkuParams() {
        const { ctx } = this;
        const { _id } = ctx.params;
        await ctx.model.SkuParams.deleteOne({ _id })
        ctx.send({ msg: "成功" })
    }
    async exSortSkuParams() {
        const { ctx } = this;
        const { _id1, _id2 } = ctx.request.body;
        const db = ctx.model.SkuParams;
        const [doc1, doc2] = await Promise.all([db.findById(_id1), db.findById(_id2)])
        let temp = doc1.sort;
        doc1.sort = doc2.sort;
        doc2.sort = temp;
        doc1.save();
        doc2.save();
        ctx.send({ msg: "成功", data: { doc1: doc1, doc2: doc2 } })
    }
}
module.exports = SkuParamsController;